<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$openid=$_W['openid'] ? $_W['openid'] : $_GPC['from_user_oauth'];


if ($operation == 'display') {
	$id = intval($_GPC['id']);
	if(empty($id))message('活动已结束！');
	$item = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_lotterygame')." WHERE id =:id ",array(':id'=>$id));
	if(empty($item))message('活动已结束！');
	if(!$openid)message("请在微信中打开游戏哦");
	$isfollow=pdo_fetchcolumn("SELECT follow FROM ".tablename('mc_mapping_fans')." WHERE openid =:openid ",array(":openid"=>$openid));
	$prizelist = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_award')." WHERE gid =:id and isprize=1 order by id desc",array(':id'=>$id));
	$prizeary=array();
	foreach($prizelist as $row){
		$prizeary[$row['id']]=$row['level'];
	}
	$isGetPrize=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_lottery')." WHERE gid =:id and from_user=:f and isprize=1 order by id asc",array(':id'=>$id,':f'=>$openid));
	$play_count=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_lottery')." WHERE gid=:a and createtime=0 and from_user=:b ",array(":a"=>$id,":b"=>$openid));		
	$flag=1;
	$gamecount=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_lottery')." WHERE gid =:id and createtime=0",array(':id'=>$id));
	if(!$gamecount){
		$flag=0;
	}
}elseif ($operation == 'getgameprize') {
	$id = intval($_GPC['id']);
	
	
	if(!$openid)message("请在微信中打开游戏哦");
	$isGetPrize=pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_lottery')." WHERE gid =:id and from_user=:f and isprize=1 order by id desc",array(':id'=>$id,':f'=>$openid));
	$prizelist = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_award')." WHERE gid =:id and isprize=1 order by id desc",array(':id'=>$id));
	$prizeary=array();
	foreach($prizelist as $row){
		$prizeary[$row['id']]=$row['level'];
	}
	for($i=0;$i<count($isGetPrize);$i++){
		$isGetPrize[$i]['prizename']=$prizeary[$isGetPrize[$i]['aid']];
	}
	die(json_encode(array('success'=>true,'list'=>$isGetPrize)));
	
}elseif ($operation == 'game') {
	$rid = intval($_GPC['id']);
	
	if(!$openid)die(json_encode(array('err'=>1,'msg'=>'微信登陆才能玩游戏哦~')));
	$play_count=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_lottery')." WHERE gid=:a and createtime=0 and from_user=:b ",array(":a"=>$rid,":b"=>$openid));
	if(!$play_count)die(json_encode(array('err'=>1,'msg'=>'您已经没有抽奖机会了哦')));
	$gameid=pdo_fetchcolumn("SELECT id FROM ".tablename('j_hmoney_lottery')." WHERE gid=:a and createtime=0 and from_user=:b order by id asc limit 1",array(":a"=>$rid,":b"=>$openid));
	$item = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_lotterygame')." WHERE id=:a ",array(":a"=>$rid));
	$list = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_award')." WHERE gid=:a and renum>0 ORDER BY id asc",array(":a"=>$rid));
	if($item['status']!=1)die(json_encode(array('err'=>1,'msg'=>'游戏已结束了哦')));
	if($item['starttime']>TIMESTAMP)die(json_encode(array('err'=>1,'msg'=>'游戏还没有开始哦')));
	if($item['endtime']<TIMESTAMP)die(json_encode(array('err'=>1,'msg'=>'游戏已结束了哦')));
	
	$prize_arr=array();
	$i=1;
	foreach($list as $row){
		$data=array(
			"id"=>$i,
			"sid"=>$row['id'],
			"title"=> $row['level'],
			"is"=> $row['isprize'],
			"deg"=>$row['deg'],
			"probalilty"=>$row['probalilty'],
		);
		array_push($prize_arr,$data);
		$i++;
	}
	$arr=array();
	foreach ($prize_arr as $key => $val) { 
		$arr[$val['id']] = $val['probalilty']; 
	}
	$proSum = array_sum($arr); 
	$result="";
	foreach ($arr as $key => $proCur) { 
		$randNum = mt_rand(1, $proSum); 
		if ($randNum <= $proCur) { 
			$result = $key; 
			break; 
		} else { 
			$proSum -= $proCur; 
		}
	}
	$res = $prize_arr[$result-1];
	$prizeItem = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_award')." WHERE id = '".$res['sid']."' ");
	if($res['is']==1 && $prizeItem['leavel']>0){
		//总参与次数
		$countman=pdo_fetchcolumn("select count(*) FROM ".tablename('j_hmoney_lottery')." WHERE gid=:a and createtime>0",array(":a"=>$rid));
		//此奖品抽中数量
		$countPrize=pdo_fetchcolumn("select count(*) FROM ".tablename('j_hmoney_lottery')." where gid=:a and aid='".$res['sid']."' ",array(":a"=>$rid));
		//总抽奖人数<（中奖要求人数*奖品已抽中数量+1）
		if($countman<$prizeItem['leavel']*($countPrize+1)){
			$other = pdo_fetch("SELECT * FROM ".tablename('j_hmoney_award')." WHERE gid = '".$rid."' and isprize=0 order by probalilty desc limit 1");
			$res['sid']=$other['id'];
			$res['level']=$other['level'];
			$res['title']=$other['title'];
			$res['deg']=$other['deg'];
			$res['credit']=$other['credit'];
			$res['is']=0;
		}
	}
	$data=array(
		'aid'=>$res['sid'],
		'award'=>$res['title'],
		"isprize"=> $res['is'],
		'createtime'=>TIMESTAMP,
	);
	$res['msg']="抱歉，没有抽奖奖品哦~";
	if($res['is']==1){
		pdo_update('j_hmoney_award', array('renum'=>$prizeItem['renum']-1,), array('id' => $res['sid']));
		//---判断中奖类型
		$cfg = $this->module['config'];
		if(strpos($prizeItem['description'],"|红包|")!==false){
			//---红包---
			$temp=str_replace("|红包|","",$prizeItem['description']);
			$favorAry=explode("-",$temp);
			$fee=0;
			if(count($favorAry)==2){
				$favorAry1=intval($favorAry[0]*100);
				$favorAry2=intval($favorAry[1]*100);
				if($favorAry1>=$favorAry2){
					$fee=$favorAry1;
				}else{
					$fee=mt_rand($favorAry1,$favorAry2);
				}
				$fee = $fee>=100 ? $fee : 100;
				$result=$this->_sendpack2($openid,$fee,$cfg);
				$data['prizetype']=1;
				$data['award']="微信现金红包";
				$data['status']=1;
				$data['sncode']=$fee;
				if(!$result || $result['errno']!=0){
					$res['msg']="恭喜您获得微信现金红包一个<br>".json_encode($result);
				}else{
					$res['msg']="恭喜您获得微信现金红包一个";
					$data['gettime']=TIMESTAMP;
				}
			}
		}elseif(strpos($prizeItem['description'],"|卡券|")!==false){
			//---卡券---
			$temp=str_replace("|卡券|","",$prizeItem['description']);
			$favorAry=strpos($temp,"|") ? explode("|",$temp) : array($temp);
			shuffle($favorAry);
			$cardkey=$favorAry[0];
			$wxcard=json_decode($cfg['wxcard'],true);
			if($wxcard[$cardkey]){
				$result=$this->sendCard($openid,$wxcard[$cardkey]);
				$data['prizetype']=2;
				$data['award']="卡券一张";
				$data['gettime']=TIMESTAMP;
				$data['status']=1;
				$data['sncode']=$wxcard[$cardkey];
				$res['msg']="恭喜您获得卡券一张";
				if($result['errno']!=0){
					$res['prizetype']=2;
					$res['sncode']=$wxcard[$cardkey];
					$res['cardary']= $this->getCardTicket($wxcard[$cardkey],$openid);
				}
			}
		}else{
			$res['msg']="恭喜您,抽中了".$res['title']." ".$prizeItem['description']."";
			$data['prizetype']=0;
			$data['sncode']=$gameid.'-'.getNonceStr(5);
		}
	}
	pdo_update('j_hmoney_lottery', $data, array('id' => $gameid));
	die(json_encode($res));
	
}elseif ($operation == 'getmyprize') {
	$rid = intval($_GPC['id']);
	
	if(!$openid)die(json_encode(array('err'=>1,'msg'=>'微信登陆才能兑奖哦~')));
	$pid=intval($_GPC['pid']);
	$item=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_lottery')." WHERE gid=:a and from_user=:b and id=:c",array(":a"=>$rid,":b"=>$openid,":c"=>$pid));
	if(!$item)die(json_encode(array('err'=>1,'msg'=>'奖品不存在~')));
	if($item['isprize']==0)die(json_encode(array('err'=>1,'msg'=>'非奖品')));
	if($item['gettime'])die(json_encode(array('err'=>1,'msg'=>'奖品已领取')));
	$game=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_lotterygame')." WHERE id=:a",array(":a"=>$rid));
	$shopid=$game['groupid'];
	$pass=($_GPC['pass']);
	$user=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE spassword=:a and pcate=:b",array(":b"=>$shopid,":a"=>$pass));
	if(!$user || !$user['status'])die(json_encode(array('err'=>1,'msg'=>'收银员密码错误')));
	pdo_update("j_hmoney_lottery",array("gettime"=>TIMESTAMP),array("id"=>$pid));
	die(json_encode(array("success"=>true)));
}

include $this->template('game');
